<script lang="ts" setup>
// 导入组件
import { ref, reactive, getCurrentInstance } from "vue";
// 引入Vue组件
import PagnationVue from "../public/Paginations.vue";
import { ElMessage, ElMessageBox } from "element-plus";
// 导入按钮图标
import { Edit, More, Delete } from "@element-plus/icons-vue";
// 导入数据的api
import Api from "../../api";
// 引入表单校验的模块
import MyRules from "../../rules/staff";
// 获取当前的实例
const { proxy } = getCurrentInstance() as any;

// 定义当前页面分页的数据
var pageData = reactive({
  page: ref(1),
  size: ref(15),
  total: ref(0),
});

// 定义页面需要绑定的数据
var Data = reactive({
  // =========== 查询区域 ============
  // 输入的查询文本
  q_str: ref(""),
  // 分部
  q_branch_options: reactive([{ id: "", name: "" }]),
  // 分部分选择值
  q_branch_selected: ref(""),
  // 业务区
  q_area_options: reactive([{ id: "", name: "" }]),
  // 业务区选择值
  q_area_selected: ref(""),
  // 场地
  q_place_options: reactive([{ code: "", name: "" }]),
  // 分部分选择值
  q_place_selected: ref(""),
  // 选择状态的值
  q_status: ref(""),

  //============ 表格区域 ===============
  staffs: reactive([]),

  // =========== 弹出层 ================
  dialogVisible: ref(false),
  layerTitle: ref(""),
  isEdit: ref(false),
  isView: ref(false),
  layerForm: reactive({
    id: ref(""),
    name: ref(""),
    pwd: ref(""),
    confirmPwd: ref(""),
    position: ref(""),
    roles:reactive([2,]),
    status: ref(false),
    placecode: reactive([]),
    mobile: ref(""),
    email: ref(""),
    create_time: ref(""),
    edit_time: ref(""),
    last_login: ref(""),
  }),
  layer_position_options: reactive([{ id: "", name: "" }]),
  layer_place_options: reactive([]),
  layer_roles_options: reactive([{ id: "", name: "" }]),

});

// 定义一个autoRun函数 -- 页面加载后自动运行
const autoRun = () => {
  // 获取分部分析填充下拉框
  getBranchs();
  // 自动获取员工信息
  getData();
  // 自动获取弹出层下拉框数据
  parpareLayerData();
};
// 自动获取分部信息
const getBranchs = () => {
  Api.Branch.getAll().then((res) => {
    // 判断
    if (res.status === 200) {
      Data.q_branch_options = res.data;
    }
  });
};

// 获取业务区
const getAreas = () => {
  // 准备请求的参数
  let params = {
    // 分部
    branch: Data.q_branch_selected,
  };
  // 请求
  Api.Area.getAll(params).then((res) => {
    // 判断
    if (res.status === 200) {
      Data.q_area_options = res.data;
    }
  });
};

//  获取场地
const getPlaces = () => {
  // 准备请求的参数
  let params = {
    // 分部
    brancharea: Data.q_area_selected,
  };
  // 请求
  Api.Place.getAll(params).then((res) => {
    // 判断
    if (res.status === 200) {
      console.log(res);
      Data.q_place_options = res.data;
    }
  });
};

// 获取所有的员工信息
const getData = () => {
  let params = {
    page: pageData.page,
    size: pageData.size,
    search: Data.q_str,
    branch: Data.q_branch_selected,
    area: Data.q_area_selected,
    areaplace: Data.q_place_selected,
    status: Data.q_status,
  };
  Api.Staff.getAll(params).then((res) => {
    // 赋值
    Data.staffs = res.data.results;
    //为分页的赋值
    pageData.total = res.data.count;
    
  });
};

// 为弹出层的职位和场地准备下拉数据   axios ---> 异步
const parpareLayerData = async () => {
  // 获取职位
  await Api.Position.getAll().then((res) => {
    Data.layer_position_options = res.data;
  });

  // 获取场地
  await Api.Place.select().then((res) => {
    Data.layer_place_options = res.data.data;
  });

  // 获取所有的角色 
  await Api.Roles.getAll({
    size:20, page:1
  }).then((res)=>{
    Data.layer_roles_options = res.data.results;
    console.log(res.data);
  })
};
// 显示全部的功能
const listAllStaffs = () => {
  // 清空所有的查询条件
  Data.q_str = "";
  Data.q_area_selected = "";
  Data.q_branch_selected = "";
  Data.q_place_selected = "";
  Data.q_status = "";
  //重新获取
  getData();
};

// 展示弹出层
const addStaff = () => {
  // 修改值
  Data.dialogVisible = true;
  // 指定标题
  Data.layerTitle = "【添加员工】";
  // 修改rules中isEdit
  MyRules.objData.isEditValue = false;
};

// 查看员工
const viewStaff = (row: any) => {
  // 修改值
  Data.dialogVisible = true;
  // 指定标题
  Data.layerTitle = "【查看员工详情】";
  // 修改isView的值
  Data.isView = true;
  // 赋值
  Data.layerForm = JSON.parse(JSON.stringify(row));
  // 处理多个场地
  Data.layerForm.placecode = row.placecode.toString().split(",");
};

// 修改员工
const editStaff = (row: any) => {
  // 修改值
  Data.dialogVisible = true;
  // 指定标题
  Data.layerTitle = "【修改员工信息】";
  // 设置IsEdit值
  Data.isEdit = true;
  // 获取当前行的值
  Data.layerForm = JSON.parse(JSON.stringify(row));
  // 赋值重复密码
  Data.layerForm.confirmPwd = row.pwd;
  // 处理多个场地
  Data.layerForm.placecode = row.placecode.toString().split(",");
  // 修改rules中isEdit
  MyRules.objData.isEditValue = true;
};

// 提交修改
const commitLayer = () => {
  // 提交的时候全部校验
  proxy.$refs.staffFormRef.validate((valid: boolean) => {
    if (valid) {
      // 所有的都符合要求！
      // 判断是添加还是修改
      if (Data.isEdit) {
        // 传值
        MyRules.objData.passwordValue = Data.layerForm.pwd;
        MyRules.objData.passwordValue = Data.layerForm.confirmPwd;
        // 修改
        Api.Staff.edit(Data.layerForm.id, Data.layerForm).then((res) => {
          if (res.status === 201) {
            // 显示成功提示
            ElMessage({
              message: "员工信息修改成功！",
              type: "success",
            });
          }
        });
      } else {
        // 添加
        Api.Staff.add(Data.layerForm).then((res) => {
          if (res.status === 201) {
            ElMessage({
              message: "员工添加成功！",
              type: "success",
            });
          }
        });
      }

      // 刷新表格
      getData();
      // 关闭
      closeLayer();
    }
  });
};

// 删除员工
const deleteStaff = (row: any) => {
  // 提示
  let confirmStr =
    "您确认要删除员工信息【编号: " + row.id + "\t姓名：" + row.name + "】信息吗？";
  // 提示
  ElMessageBox.confirm(confirmStr, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    // Ajax请求
    Api.Staff.del(row.id).then((res) => {
      if (res.status === 204) {
        // 显示成功提示
        ElMessage({
          message: "员工信息删除成功！",
          type: "success",
        });
        // 刷新数据
        getData();
      }
    });
  });
};

// 修改账号状态
const changeStatus = (event: any, row: any) => {
  Api.Staff.chStatus(row.id, { status: event }).then((res) => {
    if (res.status === 200) {
      ElMessage({
        message: "状态修改成功！",
        type: "success",
      });
    }
  });
};

// ==== 关闭弹出层 =========
const closeLayer = () => {
  // 修改值
  Data.dialogVisible = false;
  // 设置IsEdit，IsView值
  Data.isEdit = false;
  Data.isView = false;
  // 清空表格的值
  // 清空
  Data.layerForm.id = "";
  Data.layerForm.name = "";
  Data.layerForm.pwd = "";
  Data.layerForm.confirmPwd = "";
  Data.layerForm.position = "";
  Data.layerForm.place = "";
  Data.layerForm.roles = [];
  Data.layerForm.status = false;
  Data.layerForm.mobile = "";
  Data.layerForm.email = "";
  Data.layerForm.create_time = "";
  Data.layerForm.edit_time = "";
  Data.layerForm.last_login = "";
  // 清空所有表单的错误
  proxy.$refs.staffFormRef.resetFields();
};

// 输入完密码响应的时间
const completePwd = () => {
  // 赋值
  MyRules.objData.passwordValue = Data.layerForm.pwd;
};

// 自动执行
autoRun();
</script>

<template>
  <!-- 1. 查询区域 -->
  <el-form :inline="true" class="demo-form-inline" style="display: flex">
    <el-form-item label="查询条件：" width="100">
      <el-input v-model="Data.q_str" placeholder="请输入查询条件" />
    </el-form-item>
    <el-form-item label="分部:" style="width: 200px">
      <el-select
        v-model="Data.q_branch_selected"
        placeholder="请选择分部"
        clearable
        filterable
        @change="getAreas"
      >
        <el-option
          v-for="item in Data.q_branch_options"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="业务区:" style="width: 200px">
      <el-select
        v-model="Data.q_area_selected"
        filterable
        placeholder="请选择业务区"
        @change="getPlaces"
      >
        <el-option
          v-for="item in Data.q_area_options"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="场地:">
      <el-select
        v-model="Data.q_place_selected"
        placeholder="请选择场地"
        clearable
        filterable
      >
        <el-option
          v-for="item in Data.q_place_options"
          :key="item.code"
          :label="item.name"
          :value="item.code"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="状态：" style="width: 180px">
      <el-select v-model="Data.q_status" placeholder="请选择状态">
        <el-option label="请选择" value=""></el-option>
        <el-option label="启用" value="true"></el-option>
        <el-option label="停用" value="false"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getData">
        <el-icon><component class="icons" is="Search"></component></el-icon>
        <span>查询</span>
      </el-button>
      <el-button type="primary" @click="listAllStaffs">
        <el-icon><component class="icons" is="List"></component></el-icon>
        <span>全部</span>
      </el-button>
      <el-button type="primary" @click="addStaff">
        <el-icon><component class="icons" is="CirclePlus"></component></el-icon>
        <span>添加</span>
      </el-button>
    </el-form-item>
  </el-form>

  <!--2. 表格区域 -->
  <el-table
    :data="Data.staffs"
    border
    stripe
    style="width: 100%"
    :header-cell-style="{ backgroundColor: '#409EFF', color: '#FFF', fontSize: '14px' }"
  >
    <el-table-column label="序号" type="index" align="center" width="60" />
    <el-table-column label="编号" prop="id" align="center" width="100" />
    <el-table-column label="姓名" prop="name" align="center" width="100" />
    <el-table-column label="职位" prop="position.name" align="center" width="100" />
    <el-table-column label="状态" align="center">
      <template #default="scope">
        <el-switch
          v-model="scope.row.status"
          active-color="#13ce66"
          inactive-color="lightgray"
          active-text="启用"
          inactive-text="禁用"
          @change="changeStatus($event, scope.row)"
        >
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column
      label="分部"
      prop="areaplace.0.brancharea.branch.name"
      align="center"
      width="100"
    />
    <el-table-column
      label="业务区"
      prop="areaplace.0.brancharea.name"
      align="center"
      width="100"
    />
    <el-table-column
      label="场地"
      prop="placecode"
      align="center"
      width="100"
      show-overflow-tooltip
    />
    <el-table-column label="电话" prop="mobile" align="center" />
    <el-table-column label="邮箱" prop="email" align="center" />
    <el-table-column label="上次登陆" prop="last_login" align="center" />
    <el-table-column label="操作" align="center" width="200">
      <template #default="scope">
        <el-button
          type="primary"
          :icon="More"
          circle
          size="small"
          @click="viewStaff(scope.row)"
        />
        <el-button
          type="warning"
          :icon="Edit"
          circle
          size="small"
          @click="editStaff(scope.row)"
        />
        <el-button
          type="danger"
          :icon="Delete"
          circle
          size="small"
          @click="deleteStaff(scope.row)"
        />
      </template>
    </el-table-column>
  </el-table>

  <!--3. 分页  -->
  <PagnationVue :page="pageData"></PagnationVue>

  <!--4. 弹出层 -->
  <el-dialog v-model="Data.dialogVisible" width="45%" @close="closeLayer">
    <!--标题部分-->
    <template #title>
      <div style="font-size: 18px; color: #409eff; font-weight: bold; text-align: left">
        {{ Data.layerTitle }}
      </div>
    </template>

    <!--表单部分-->
    <el-form
      :model="Data.layerForm"
      :inline="true"
      class="demo-form-inline"
      label-width="100px"
      :rules="MyRules.rulesDetail"
      ref="staffFormRef"
    >
      <el-form-item label="工号：" prop="id">
        <el-input
          v-model="Data.layerForm.id"
          :suffix-icon="Edit"
          :disabled="Data.isView || Data.isEdit"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="姓名：" prop="name">
        <el-input
          v-model="Data.layerForm.name"
          :suffix-icon="Edit"
          :disabled="Data.isView"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="密码：" v-show="!Data.isView" prop="pwd">
        <el-input
          v-model="Data.layerForm.pwd"
          :suffix-icon="Edit"
          type="password"
          placeholder="请输入"
          @blur="completePwd"
        />
      </el-form-item>
      <el-form-item label="重复密码：" v-show="!Data.isView" prop="confirmPwd">
        <el-input
          v-model="Data.layerForm.confirmPwd"
          :suffix-icon="Edit"
          type="password"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="职位：" prop="position">
        <el-select
          v-model="Data.layerForm.position"
          placeholder="请选择职位"
          clearable
          filterable
          :disabled="Data.isView"
        >
          <el-option
            v-for="item in Data.layer_position_options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <template #default="scope">
          <el-switch
            :disabled="Data.isView"
            v-model="Data.layerForm.status"
            active-color="#13ce66"
            inactive-color="lightgray"
            active-text="启用"
            inactive-text="禁用"
            style="width: 212px"
            @change=""
          >
          </el-switch>
        </template>
      </el-form-item>
      <el-form-item label="角色：" prop="position">
        <el-select
          v-model="Data.layerForm.roles"
          placeholder="请选择角色"
          clearable
          filterable
          multiple
          :disabled="Data.isView"
          style="width: 555px; height: auto"
        >
          <el-option
            v-for="item in Data.layer_roles_options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="场地：" prop="placecode">
        <el-cascader
          :options="Data.layer_place_options"
          v-model="Data.layerForm.placecode"
          :disabled="Data.isView"
          :props="{ multiple: true }"
          :show-all-levels="false"
          collapse-tags
          collapse-tags-tooltip
          placeholder="选择场地"
          filterable
          clearable
          style="width: 555px; margin-bottom: 20px; height: auto"
        />
      </el-form-item>
      <el-form-item label="电话：" prop="mobile">
        <el-input
          v-model="Data.layerForm.mobile"
          :suffix-icon="Edit"
          :disabled="Data.isView"
          placeholder="请输入"
        />
      </el-form-item>
      <el-form-item label="邮箱：" prop="email">
        <el-input
          v-model="Data.layerForm.email"
          :suffix-icon="Edit"
          :disabled="Data.isView"
          placeholder="请输入"
        />
      </el-form-item>

      <el-form-item label="创建时间：">
        <el-date-picker
          v-model="Data.layerForm.create_time"
          disabled
          type="datetime"
          style="width: 212px"
        />
      </el-form-item>
      <el-form-item label="修改时间：">
        <el-date-picker
          v-model="Data.layerForm.edit_time"
          disabled
          type="datetime"
          style="width: 212px"
        />
      </el-form-item>
      <el-form-item label="上次登录：" style="float: left; margin-left: 67px">
        <el-date-picker
          v-model="Data.layerForm.last_login"
          disabled
          type="datetime"
          style="width: 212px"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" v-show="!Data.isView" @click="commitLayer"
          >提交</el-button
        >
        <el-button @click="closeLayer">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped></style>
